import { getUuid } from '@/system/utils/UuidUtils';
import { Drawer } from 'antd';
import ReactDOM from 'react-dom';
import React, { Suspense } from 'react';
import { SyncOutlined } from '@ant-design/icons';
import { notice } from '@/system/components/Notice';

/**
 * 默认抽屉配置
 */
const defaultDrawerConfig = {
  maskClosable: false,
  width: 444,
  keyboard: true,
};
/**
 * 抽屉
 */
export const MonsterDrawer = {
  show: (options: any | null) => {
    if (options == null || options.url == '') {
      notice.warning('抽屉', '缺少必要弹出信息,无法弹出抽屉');
      return;
    }

    const id = 'drawer' + getUuid();
    const div = document.createElement('div');
    div.setAttribute('id', id);
    document.body.appendChild(div);

    const MonsterDrawer = () => {
      // 合并属性
      options = Object.assign(defaultDrawerConfig, options);
      // 重构方法
      const onClose = options.onClose;
      delete options.onClose;
      // 懒加载对象
      const Window = React.lazy(() => import(`@/pages/${options.url}`));
      // 窗口关闭事件
      const onCloseFun = (data: any) => {
        ReactDOM.unmountComponentAtNode(div);
        if (onClose instanceof Function) {
          onClose(data);
        }
      };
      // 懒加载
      const drawer = (
        <Drawer
          key={'Drawer' + id}
          visible={true}
          {...options}
          onClose={() => {
            onCloseFun(null);
          }}
        >
          <Suspense key={'Suspense' + id} fallback={<SyncOutlined spin />}>
            <Window
              data={options.data}
              close={(data: any) => {
                onCloseFun(data);
              }}
            />
          </Suspense>
        </Drawer>
      );
      return drawer;
    };
    ReactDOM.render(
      <MonsterDrawer key={'MonsterDrawer' + id} />,
      document.getElementById(id),
    );
  },
};
